package com.xiaolei48.controller;

import com.xiaolei48.entity.Foods;
import com.xiaolei48.service.FoodsService;
import com.xiaolei48.utils.ResponseResult;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/foods")
@CrossOrigin
public class FoodsController {

    private static final Logger log = LoggerFactory.getLogger(FoodsController.class);

    @Autowired
    private FoodsService foodsService;

    // 从配置文件读取端口（实际配置为8001）
    @Value("${server.port}")
    private int serverPort;


    // ========== 原有接口保持不变 ==========
    @PostMapping("/add.do")
    public ResponseResult addFoodsInfo(@RequestBody Foods foods) {
        log.info("添加菜品 - 端口: {}", serverPort);
        try {
            boolean result = foodsService.doAddFoodsInfo(foods);
            return ResponseResult.build(result, result ? "添加成功" : "添加失败", null);
        } catch (Exception e) {
            log.error("添加菜品异常", e);
            return ResponseResult.build(false, "系统繁忙，请稍后再试", null);
        }
    }

    @PostMapping("/modify.do")
    public ResponseResult modifyFoodsInfo(@RequestBody Foods foods) {
        log.info("修改菜品 - 端口: {}", serverPort);
        try {
            boolean result = foodsService.doModifyFoodsInfo(foods);
            return ResponseResult.build(result, result ? "修改成功" : "修改失败", null);
        } catch (Exception e) {
            log.error("修改菜品异常", e);
            return ResponseResult.build(false, "系统繁忙，请稍后再试", null);
        }
    }

    @PostMapping("/delete.do")
    public ResponseResult deleteFoodsInfo(@RequestBody Foods foods) {
        log.info("删除菜品 - 端口: {}", serverPort);
        try {
            boolean result = foodsService.doDeleteFoodsInfo(foods);
            return ResponseResult.build(result, result ? "删除成功" : "删除失败", null);
        } catch (Exception e) {
            log.error("删除菜品异常", e);
            return ResponseResult.build(false, "系统繁忙，请稍后再试", null);
        }
    }

    @PostMapping("/get.do")
    public ResponseResult getFoodsInfo(@RequestBody Foods foods) {
        log.info("查询单个菜品 - 端口: {}", serverPort);
        try {
            Foods result = foodsService.doGetFoodsInfo(foods);
            return ResponseResult.build(result != null, null, result);
        } catch (Exception e) {
            log.error("查询单个菜品异常", e);
            return ResponseResult.build(false, "系统繁忙，请稍后再试", null);
        }
    }

    @PostMapping("/query.do")
    public ResponseResult queryFoodsInfoList(@RequestBody Foods foods) {
        log.info("条件查询菜品 - 端口: {}", serverPort);
        try {
            List<Foods> list = foodsService.doQueryFoodsInfoList(foods);
            return ResponseResult.build(list != null, null, list);
        } catch (Exception e) {
            log.error("条件查询菜品异常", e);
            return ResponseResult.build(false, "系统繁忙，请稍后再试", null);
        }
    }


    // ========== 重点：list.do 加熔断 ==========
    @GetMapping("/list.do")
    @CircuitBreaker(
            name = "menuService",      // 熔断实例名，需和配置文件对应
            fallbackMethod = "listFallback" // 降级方法
    )
    public ResponseResult getFoodsInfoList() {
        log.info("获取菜品列表 - 端口: {}", serverPort);
        try {
            List<Foods> list = foodsService.doGetFoodsInfoList();
            return ResponseResult.build(list != null, null, list);
        } catch (Exception e) {
            log.error("获取菜品列表异常（触发熔断检测）", e);
            throw e; // 抛出异常，让熔断捕获
        }
    }

    // 熔断降级方法（参数必须匹配异常类型）
    private ResponseResult listFallback(Throwable ex) {
        log.warn("熔断触发！端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(false,
                "服务繁忙，请稍后再试（来自端口：" + serverPort + "）",
                null
        );
    }


    // ========== 测试接口（可选） ==========
    @GetMapping("/test-circuit-breaker")
    public ResponseResult testCircuitBreaker() {
        log.info("测试熔断 - 端口: {}", serverPort);
        try {
            List<Foods> list = foodsService.doGetFoodsInfoList();
            return ResponseResult.build(true, "操作成功（端口：" + serverPort + "）", list);
        } catch (Exception e) {
            return ResponseResult.build(false, "服务暂时不可用（可能触发熔断）", null);
        }
    }
}